package com.riant.aop;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.commons.codec.binary.Base64;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RsaUtil {

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 512;
    /**
     * 用于封装随机产生的公钥与私钥
     */
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();

    public static void main(String[] args) {
        String privateStr="MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAivVFrjkNMh+Yfm0+V30lPMT3Tiia2uk7bUtwuYEVh2tCCOjycrw+4uWsLS5L2+QzIweBuZjuFzlm7RCvmGF8xQIDAQABAkBY5ME3zC2B5C6EqlQYWempb4OZj2ZJJq0qpPku4sIoB1wnB3rn25r3UQ/tzbp2+v2DU1q7b0q/xAg7SlapSiI9AiEA/xn0OWuh0KTBAgpDU9ahTtdbmy49cqbAw5deP0TL7NsCIQCLcpUKOBPWSrjBXv+OnjxWPYldJr8NzZ8shPxROV2e3wIgcq4iQqYGSpumQNqIRepY/e6Gug5hhWc9hTBJKDwvSL0CIG1MmlUwLxw/5SBr/ZMjo9dU1F4XCJkhGioi8kIX3LGxAiEA/Ytdc35H1wM6XzqSAfCLhx7i3vq9VOw8yCwDpJXxhFY=";
        String publicStr="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIr1Ra45DTIfmH5tPld9JTzE904omtrpO21LcLmBFYdrQgjo8nK8PuLlrC0uS9vkMyMHgbmY7hc5Zu0Qr5hhfMUCAwEAAQ==";
        PrivateKey privateKey = getPrivateKeyFromStr(privateStr);
        PublicKey publicKey = getPublicKeyFromStr(publicStr);
        System.out.println("privateKey alg:"+privateKey.getAlgorithm());
        System.out.println("publicKey alg:"+publicKey.getAlgorithm());
        String signature = TestSignature.signatureBySHA1withRSA(privateKey, "hello");
        System.out.println("signature:"+signature);
        boolean result = TestSignature.verifyBySHA1withRSA(publicKey, "hello", signature);
        System.out.println("vefify result:"+result);

//        try {
//            genKeyPair();
//            String privateKeyStr = keyMap.get(0);
//            String publicKeyStr = keyMap.get(1);
//            //TestSignature.signatureBySHA1withRSA()
//
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public  static void genKeyPair() throws NoSuchAlgorithmException, IOException {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString =Base64.encodeBase64String(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
        // 将公钥和私钥保存到Map
        //0表示公钥
        keyMap.put(0, publicKeyString);
        //1表示私钥
        keyMap.put(1, privateKeyString);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("PubKey.key"));
        osw.write(publicKeyString);
        osw.flush();
        osw.close();
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("PriKey.key"));
        osw2.write(privateKeyString);
        osw2.flush();
        osw2.close();

    }

    public static PrivateKey getPrivateKeyFromStr(String message){
        byte[] bytes = Base64.decodeBase64(message);
        PrivateKey privateKey=null;
        PKCS8EncodedKeySpec x509EncodedKeySpec = new PKCS8EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(x509EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return privateKey;
    }
    public static PublicKey getPublicKeyFromStr(String message){
        byte[] bytes = Base64.decodeBase64(message);
        PublicKey publicKey=null;
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }
}
